<script setup>
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox,ElLoading  } from 'element-plus';
import { queryCouponsDetails,couponsActivityRule,couponsReceiveDetails } from '@/api/Marketing/coupon.js'
import { newUserActivityOperate,getNewUserActivityDetail } from '@/api/OperationManage/marketingManagements'
import { exportFile } from '@/utils/common.js';
import TopBar from '@/components/Topbar/index.vue';
import getRules from "@/validUtils";
import { getMemberLevelList } from '@/api/Member/index.js' 
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const topbarRef = ref(null);

const backValue = ref('ShopActivityIndex');
const tabName = ref("查看折扣详情");

const formRef = ref(null);



const activityRef = ref(null);
const storeList = ref([]);
const groupType = ref("疗程")
// const form = ref({
//     name:"",
//     remark:"",
//     sendNum:"",
//     price:"",
//     useThreshold:0,
//     reachPrice:"",
//     useTime:0,
//     useTimeValue:["",""],
//     useDay:"",
//     useStore:0,
//     needValue:"1",
//     storeList:[]
// })


const cycleList = computed(() => {
        if(form.value.activityCycleType == 0){
            let cycleList = [];
            for(let i = 1;i<=7;i++){
                let weetText = ["","一","二","三","四","五","六","日"];
                cycleList.push({
                    value:Number(i),
                    label:'周'+weetText[i]
                })
            }
            return cycleList;
        }else if(form.value.activityCycleType == 1){
            let cycleList = [];
            for(let i = 1;i<=31;i++){
                cycleList.push({
                    value:Number(i),
                    label:i+'日'
                })
            }
            return cycleList;
        }
})

/**
 * ===========会员等级参数===========
 */
 const options = ref([])

const getMembershipLevel = async() => {
   const res = await getMemberLevelList()
   options.value = res.map(item => {
      return{
        value:item.id,
        label:item.levelName
      }
   })
   console.log(options.value,'options.value');
}

/**
 * ===========会员等级参数========
 */

const form = ref({
    activeName: '',
    activeDateType: 0,
    activeDate: null,
    // useStore: 1,
    isRestriction:0, //是否限购
    activeObject:0, //活动对象
    memberType:false, //会员类型
    membershipLevel:[], //会员等级
    rangeActive:0, //活动范围
    discount:'', //折扣
    availablGoods:'', //可用商品折扣
    activityCycleType:0,
    chooseRadius:true,//百分比或折后
    useStore:0, // 全部门店或指定
  })

const activityScopeList = ['全部商品可用','指定商品可用','指定商品不可用']
const activityForm = ref({
    rangeType:0,
    cureList:[],
    comboList:[],
    projectList:[],
    productList:[]
})
const activeType = ref("基本信息");






const storePageConfig = ref({
    nowPage:1,
    pageSize:3,
    totalPage:0
})

const _getStoreLsit = async (page)=>{
    storePageConfig.value.nowPage = page;
    let parmas = {
        page:storePageConfig.value.nowPage,
        pageSize:storePageConfig.value.pageSize,
    }
    let result = await getLimitData(parmas,form.value.storeList);
    result =  JSON.parse(result);
    storeList.value = result.data
    storePageConfig.value.totalPage = Number(result.totalPage);
}

//获取分页后的数据
const getLimitData = (params,arr=[]) =>{
    const self = this;
    return new Promise((resolve,reject)=>{
        let returnData = JSON.parse(JSON.stringify(arr));
        params.page = params.page-1;
        let atPage = params.page * params.pageSize;
        returnData = returnData.splice(atPage,params.pageSize);
        resolve(JSON.stringify({
            data:returnData,
            totalPage:arr.length
        }));
    })
};


const groupTypeChange = ()=>{
    _getRangeList(1);
}



const rangePageConfig = ref({
    nowPage:1,
    pageSize:5,
    totalPage:0
})
const rangeList = ref([]);
const _getRangeList = async (page)=>{
    rangePageConfig.value.nowPage = page;
    let parmas = {
        page:rangePageConfig.value.nowPage,
        pageSize:rangePageConfig.value.pageSize,
    }
    let arr = [];
    if(groupType.value == "疗程"){
        arr = activityForm.value.cureList;
    }else if(groupType.value == "套餐"){
        arr = activityForm.value.comboList;
    }else if(groupType.value == "项目"){
        arr = activityForm.value.projectList;
    }else if(groupType.value == "产品"){
        arr = activityForm.value.productList;
    }

    let result = await getLimitData(parmas,arr);
    result = JSON.parse(result);
    rangeList.value = result.data;
    rangePageConfig.value.totalPage = Number(result.totalPage);
}
const searchData = ref({})

const formInline = ref([

])

const btnLefts = ref([
    {
        label:"导出",
        plain:false,
        type:"primary",
        show:true,
        plain:true,
        img:new URL("@/assets/icon/btn-export.png",import.meta.url),
        style:"border-color:#0C268C;color:#0C268C",
        click:async ()=>{
            const loading = ElLoading.service({
                lock: true,
                text: '导出中',
                background: 'rgba(255, 255, 255, 0.7)',
            })
            try{

              await exportFile(`/jy-marketing/mgmt/marketing/coupons/couponsReceiveDetExport`,'post',`优惠券领取详情`,{},searchData.value);
              loading.close()
            }catch(e){
              
              loading.close()
            }
        }
    },
])
const btnRights = ref([
])

const tableConfig = ref([
    {
      prop: "userName",
      label: "领取人姓名",
    },
    {
      prop: "phone",
      label: "手机号",
    },
    {
      prop: "receiveTime",
      label: "领取时间",
    },
    {
      prop: "applyTime",
      label: "使用时间",
    },
    {
        type: 'slot',
        label: '状态',
        prop: 'status',
        width: 140,
        needHeader: true,
        slotHeaderName: 'statusHeader',
        slotName: 'status'
    },

]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const seachTable = ref(null);

const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{

        let params = {
            ...formInline,
            couponsId:uuid.value,
            couponsStatus:status.value == -1?"":status.value
        }
        searchData.value = params;  
        let result = await couponsReceiveDetails(params);
 
        totalPage.value = Number(result.total);
        tableData.value = result.records;
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const status = ref(-1);
const handleCommand = (name) => {
    status.value = name;
    seachTable.value.initSearch();
};
const pageLoading = ref(false);
const uuid = ref(route.query.id || "");
const _queryCouponsDetails = async ()=>{
    pageLoading.value = true;
    try{
        let data = {
            activityType:'2',
            activityId:uuid.value,
        }
        await getMembershipLevel()
        let res = await getNewUserActivityDetail(data);
        console.log(res,222);


        form.value.activeName = res.activityName
        form.value.activeDateType = res.activityTimeType
        form.value.activityCycleType = res.timeCycleType
        form.value.isRestriction = res.isLimited ? 1 : 0
        form.value.activeObject = res.activityMember
        form.value.rangeActive =   res.activityRule
        form.value.chooseRadius = res.discountsType ? true : false
        activityForm.value.rangeType = res.activityRule;
        console.log(activityForm.value.rangeType,'activityForm.value.rangeType');
        if(res.activityTimeType){
        form.value.activeDate = `${res.activityStartTime} - ${res.activityEndTime}`
        }else{

        let dateFilter = res?.timeCycleTypeData?.map(item=>cycleList.value[item - 1].label) ?? []
        form.value.activeDate = dateFilter.join('、')
        }
        if(res.activityMember == 0){
        // 全部会员
        form.value.memberType = res.activityMemberType ? true : false
        
        }else{
        // 指定会员
        console.log(options.value,'options.value');
        form.value.membershipLevel = options.value.filter((v) => res.memberLevelIdSet.includes(v.value)).map(item => item.label).join('、') 
        console.log(form.value.membershipLevel, res.memberLevelIdSet,'res.activityMemberLevelData'); 
        }
        form.value.useStore = res.businessScope
        switch (res.activityRule) {
          case 0:
            console.log('zhixing');
           form.value.discount = res.discounts
            break;
          // case 1:
          //   params.discounts = ''
          //   break;
          case 2:
            form.value.availablGoods = res.discounts
            break;  
          default:
            break;
        }
 
        if(res.activityStoreData && res.activityStoreData.length>0){

            form.value.storeList = res.activityStoreData.map(value=>{
                return {
                    id:value.storeId,
                    storeName:value.storeName,
                    isHall:value.businessType.includes(1),
                    isShop:value.businessType.includes(2),
                    hallId:'hall'+value.storeId,
                    shopId:'shop'+value.storeId,
                }
            })
            _getStoreLsit(1);
        }
         _couponsActivityRule(res);
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
_queryCouponsDetails();

const _couponsActivityRule = (res)=>{
    pageLoading.value = true;
    try{
        let result = res.activityRuleData;
        console.log(result,'result');
        result.forEach(lis=>{
            if(lis.activityType == 7){
         
                activityForm.value.cureList = lis.ruleData.map(info=>{
                    return {
                        courseName:info.productName,
                        id:info.id,
                        discount: res.discountsType ? info.discountedPrices : '',
                        discountPrice: res.discountsType == 0 ? info.discountedPrices : '',
                        cumulatePrice: info.limitCount || '',
                    }
                })
            }
            if(lis.activityType == 3){
                activityForm.value.comboList = lis.ruleData.map(info=>{
                    return {
                        comboName:info.productName,
                        id:info.id,
                        discount: res.discountsType ? info.discountedPrices : '',
                        discountPrice: res.discountsType == 0 ? info.discountedPrices : '',
                        cumulatePrice: info.limitCount || '',
                    }
                })
            }
            if(lis.activityType == 2){
                activityForm.value.projectList = lis.ruleData.map(info=>{
                    return {
                        projectName:info.productName,
                        id:info.id,
                        discount: res.discountsType ? info.discountedPrices : '',
                        discountPrice: res.discountsType == 0 ? info.discountedPrices : '',
                        cumulatePrice: info.limitCount || '',
                    }
                })
            }
            if(lis.activityType == 1){
                activityForm.value.productList = lis.ruleData.map(info=>{
                    return {
                        productName:info.productName,
                        id:info.id,
                        discount: res.discountsType ? info.discountedPrices : '',
                        discountPrice: res.discountsType == 0 ? info.discountedPrices : '',
                        cumulatePrice: info.limitCount || '',
                    }
                })
      
            }
        })
        _getRangeList(1);
  
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
onActivated(()=>{
    if(uuid.value !== route.query.id){
        uuid.value = route.query.id;
        activeStep.value = 0;
        _queryCouponsDetails();
    }

}) 
</script>
<template>
    <div class="page-contain">
        <TopBar :backValue="backValue" :tabName="tabName" ref="topbarRef">
        </TopBar>
        <div class="info-contain" v-loading="pageLoading">
            <div style="width:100%;padding-bottom:10px;">
                <el-radio-group v-model="activeType">
                    <el-radio-button label="基本信息" />
                    <el-radio-button label="活动规则" />
                </el-radio-group>
            </div>
            <div style="width:100%" v-if="activeType == '基本信息'">
                <el-form :model="form" label-width="130px" ref="formRef">
                    <div class="form-contain">
                        <el-form-item label="活动名称：" prop="name">
                            {{ form.activeName || '-' }}
                        </el-form-item>
                        <el-form-item label="活动时间：" prop="remark">
                            {{ form.activeDate || '-' }}
                        </el-form-item>
                        <el-form-item label="是否限购：" prop="sendNum">
                            {{ form.isRestriction ? '是' : '否' || '-' }}
                        </el-form-item>
                        <el-form-item label="活动对象：" prop="price">
                            {{ form.activeObject ? '指定会员等级' : '全部会员' || '-' }}
                            <div v-if="form.activeObject == 0">({{ form.memberType ? '未消费会员' : '全部' || ''}})</div>
                            <div v-else>({{ form.membershipLevel }})</div>
                        </el-form-item>

                        <el-form-item label="适用门店及业务：" >
                            <span v-if="form.useStore == 0">全部门店及业务</span>
                            <span v-if="form.useStore == 1">指定门店及业务</span>
                        </el-form-item>
                        <el-form-item label="选择门店："  v-if="form.useStore == 1">

                            <div style="width:100%;padding-bottom:24px">
                            
                                <div style="width:500px;margin-top:8px" v-if="storeList && storeList.length>0">
                                    <el-table :data="storeList" style="width: 100%" stripe>
                                        <el-table-column prop="storeName" label="门店名称" width="500">
                                        </el-table-column>
                                        <!-- <el-table-column label="理疗馆">
                                            <template #default="{ row }">
                                                <span v-if="row.isHall">√</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="商城">
                                            <template #default="{ row }">
                                                <span v-if="row.isShop">√</span>
                                            </template>
                                        </el-table-column> -->
                                    </el-table>
                                    <div class="page">
                                        <el-pagination
                                            :current-page="storePageConfig.nowPage"
                                            :page-size="storePageConfig.pageSize"
                                            layout="prev, pager, next"
                                            :total="storePageConfig.totalPage"
                                            background
                                            @current-change="_getStoreLsit">
                                        </el-pagination>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div style="width:100%" v-if="activeType == '活动规则'">
                <el-form :model="activityForm" label-width="90px"  ref="activityRef">
                    <el-form-item label="活动范围：" >
                        <div>{{ activityScopeList[activityForm.rangeType] }}</div>
                        <div v-if="activityForm.rangeType == 0">-折扣{{form.discount}}%</div>
                    </el-form-item>
                   <el-form-item>
                    <div v-if="activityForm.rangeType == 1">
                        <div v-if="form.chooseRadius">百分比折扣</div>
                        <div v-if="!form.chooseRadius">固定价格</div>
                    </div>
                    
                        <div v-if="activityForm.rangeType == 2">可用商品折扣：{{form.availablGoods}}%</div> 
                   </el-form-item>
                    <div>
                        <div style="width:100%;" v-if="activityForm.rangeType !== 0">
                            <el-radio-group v-model="groupType" @change="groupTypeChange">
                                <el-radio-button label="疗程" />
                                <el-radio-button label="套餐" />
                                <el-radio-button label="项目" />
                                <el-radio-button label="产品" />
                            </el-radio-group>
                        </div>
                    <div style="width:500px;margin-top:8px" v-if="rangeList && rangeList.length>0">
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '疗程'">
                                <el-table-column prop="courseName" label="疗程名称" >
                                </el-table-column>
                                <el-table-column v-if="form.chooseRadius && activityForm.rangeType == 1" prop="discount" label="折扣" >
                                </el-table-column>
                                <el-table-column v-if="!form.chooseRadius && activityForm.rangeType == 1" prop="discountPrice" label="折后价">
                                </el-table-column>
                                <el-table-column v-if="form.isRestriction" prop="cumulatePrice" label="累计限购">
                                </el-table-column>
                            </el-table>
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '套餐'">
                                <el-table-column prop="comboName" label="套餐名称">
                                </el-table-column>
                                <el-table-column v-if="form.chooseRadius && activityForm.rangeType == 1" prop="discount" label="折扣" >
                                </el-table-column>
                                <el-table-column v-if="!form.chooseRadius && activityForm.rangeType == 1" prop="discountPrice" label="折后价">
                                </el-table-column>
                                <el-table-column v-if="form.isRestriction" prop="cumulatePrice" label="累计限购">
                                </el-table-column>
                            </el-table>
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '项目'">
                                <el-table-column prop="projectName" label="项目名称">
                                </el-table-column>
                                <el-table-column v-if="form.chooseRadius" prop="discount" label="折扣" >
                                </el-table-column>
                                <el-table-column v-if="!form.chooseRadius" prop="discountPrice" label="折后价">
                                </el-table-column>
                                <el-table-column v-if="form.isRestriction" prop="cumulatePrice" label="累计限购">
                                </el-table-column>
                            </el-table>
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '产品'">
                                <el-table-column prop="productName" label="产品名称">
                                </el-table-column>
                            </el-table>
                            <div class="page">
                                <el-pagination
                                    :current-page="rangePageConfig.nowPage"
                                    :page-size="rangePageConfig.pageSize"
                                    layout="prev, pager, next"
                                    :total="rangePageConfig.totalPage"
                                    background
                                    @current-change="_getRangeList">
                                </el-pagination>
                            </div>
                        </div>
                    </div>
                  
                </el-form>

            </div>
        </div>
    </div>

</template>
<style lang="less" scoped>
.status-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color:#000;
    position: relative;
    top:3px;
    img{
        width: 14px;
        height: 14px;
        cursor: pointer;
        margin-left:4px;
    }
}
.page{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  margin-top:8px;
}
:deep(.el-table__inner-wrapper::before){
    display:none;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}

:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
.inline-class{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.unit-class{
    font-size: 14px;
    color: #000000;
    font-weight: 400;
    line-height: 32px;
    margin-left:8px;
}
.form-contain{
    width: 100%;

}
.page-contain{
    width: 100%;
    height: 100%;
}
.info-contain{
    width: 100%;
    height: calc(100% - 48px);
    box-sizing: border-box;
    padding:16px 24px;
    :deep(.el-form-item){
        margin-bottom:0;
    }
    :deep(.el-form-item__label){
        padding:0;
    }
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3480FF;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
:deep(.search-line){
    padding:0;
}
:deep(.search-table .table){
    padding:0;
    padding-top:12px;
}
:deep(.search-table .btn-area){
    padding:0;

}
</style>